package com.qidi.ssh.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.qidi.ssh.bean.User;
import com.qidi.ssh.service.UserService;
import net.sf.json.JSONArray;
import org.apache.struts2.ServletActionContext;

import java.io.IOException;
import java.util.List;

/**
 * @author zhouXinBin
 * @create 2020-10-16-12:03
 */
public class UserAction extends ActionSupport implements ModelDriven<User> {
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public User user=new User();

    @Override
    public User getModel() {
        return user;
    }
    public String regist(){
        userService.regist(user);
        return LOGIN;
    }
    public String login(){
        User user = userService.login(this.user);
        if (user!=null){
            ServletActionContext.getRequest().getSession().setAttribute("user",user);
            return SUCCESS;
        }else {
            this.addActionError("用户名或密码错误！");
            return LOGIN;
        }
    }
    public String findAllUser() throws IOException {
        List<User> list = userService.findAllUser();
        JSONArray jsonArray = JSONArray.fromObject(list);
        ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
        ServletActionContext.getResponse().getWriter().write(jsonArray.toString());
        return NONE;
    }
}
